package com.acme.domain.email.impl;

import java.util.ArrayList;
import java.util.List;
import com.acme.domain.email.*;

public class QueueImpl <T> implements Queue <T> {

	List<T> items = new ArrayList<T>();
	private Object monitor = new Object();
	boolean close;

	int maxCapacity;

	public QueueImpl(int maxCapacity) {
		this.maxCapacity = maxCapacity;
	}

	public void addEmail(T email) {
		try {
			synchronized (monitor) {
				if (close) {
					System.out.println("Mail is ignored, queue is closed");
					return;
				}
				while ((items.size() >= maxCapacity)) {
					if (close) {
						System.out.println("Mail is ignored, queue is closed");
						return;
					}
					monitor.wait();
				}
				if (items.size() < maxCapacity) {
					items.add((T) email);
					monitor.notify();
				}
			}
		} catch (InterruptedException e) {
		}
	}

	public void close() {
		close = true;
		synchronized (monitor) {
			monitor.notifyAll();
		}

	}

	public T getEmail() {
		synchronized (monitor) {
			if (items.isEmpty()) {
				while (items.isEmpty() && !close) {
					try {
						monitor.wait();
					} catch (InterruptedException e) {
					}
				}
			}
			if (!items.isEmpty()) {
				T mail = (T) items.remove(0);
				monitor.notify();
				System.out.println("get email from the queue");
				return mail;
			} else
				return null;
		}
	}
}
